package org.file5.controller;

import java.io.IOException;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.file5.domain.Article;
import org.file5.domain.BaseEntity;
import org.file5.service.ServiceFascade;
import org.file5.util.DataBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;

@Controller
public class HomeController {
	private final Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private ServiceFascade sf;
	@Autowired
	private UserService googleUserService;

	@RequestMapping(value = "/help", method = RequestMethod.GET)
	public String help() {
		return "help";
	}

	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home(Model model) {
		DataBean<Article> db = sf.getArticleService().getArticlesByProperties(0,1,"pubadv",true);
		if (db.getData() != null && !db.getData().isEmpty()) {
			model.addAttribute("pubadvArticles", db.getData());
		}

		DataBean<Article> db1 = sf.getArticleService().getArticlesByProperties(0,5,"topped",true);
		if (db1.getData() != null && !db1.getData().isEmpty()) {
			model.addAttribute("toppedArticles", db1.getData());
		}

		DataBean<Article> dataBean = sf.getArticleService().getArticles(0, 50,
				null, BaseEntity.STATUS.ONLINE);
		if (dataBean != null && !dataBean.isEmpty()) {
			model.addAttribute("articles", dataBean.getData());
		}

		return "home";
	}

	@RequestMapping(value = "/mycommentsback", method = RequestMethod.GET)
	public String mycommentsback() {
		return "mycommentsback";
	}

	@RequestMapping("/logout")
	public String logout(Model model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Random r = new Random();
		User googleUser = googleUserService.getCurrentUser();
		model.addAttribute("axschema", googleUser);
		model.addAttribute("logoutUrl", googleUserService.createLogoutURL("/")
				+ "&r=" + r.nextFloat());

		request.getSession().removeAttribute("isBuddy");
		request.getSession().removeAttribute("googleUser");

		return "logout";
	}

}
